package client

import (
	"context"
	"google.golang.org/grpc"
	user "short-video/common/proto"
)

type Handler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8082", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, nil
}
func VideoList(ctx context.Context, i *user.VideoListReq) (*user.VideoListResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		list, err := in.VideoList(ctx, i)
		if err != nil {
			return nil, err
		}
		return list, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.VideoListResp), nil
}
func UserCenter(ctx context.Context, i *user.UserCenterReq) (*user.UserCenterResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		center, err := in.UserCenter(ctx, i)
		if err != nil {
			return nil, err
		}
		return center, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserCenterResp), nil
}

func AddVideo(ctx context.Context, i *user.AddVideoReq) (*user.AddVideoResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		video, err := in.AddVideo(ctx, i)
		if err != nil {
			return nil, err
		}
		return video, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.AddVideoResp), nil
}
